package com.syl.springcloud.authorization.service;

import com.syl.springcloud.authorization.bean.ReturnMessage;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.security.web.session.InvalidSessionStrategy;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 提供rest 方式的登录失效提示
 * @author syl
 * @create 2018-08-13 15:12
 **/
@Component
public class RestSessionExpiredStrategy implements InvalidSessionStrategy {

    @Override
    public void onInvalidSessionDetected(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        returnJson(response,new ReturnMessage(401,"您的登录已超时"));
    }

    private void returnJson(HttpServletResponse response, ReturnMessage msg) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        try {
            response.getWriter().println(new ObjectMapper().writeValueAsString(msg));
            response.flushBuffer();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
